/* 引入模块 */
var webpack           = require('webpack'),
    path              = require('path'),
    glob              = require('glob'),
    HtmlWebpackPlugin = require('html-webpack-plugin'),
    ExtractTextPlugin = require('extract-text-webpack-plugin');

/* 方法定义 */
// 遍历数组中的路径，并以文件名作为 key ，路径作为 value
Array.prototype.getEntryFiles = function() {
  var entryFiles  = {};

  for (var i = 0, len = this.length; i < len; i += 1) {
      entryFiles[path.basename(this[i], '.js')] = this[i];
  }

  return entryFiles;
};

// 获取新建网页的参数 并实例化，压入一个数组
Array.prototype.getHtmlFiles = function() {
  var html  = [];

  for (var i = 0, len = this.length; i < len; i += 1) {
    html.push(new HtmlWebpackPlugin(require(this[i])));
  }

  return html;
};

/* 变量初始化 */
var plugins         = [],
    src             = path.join(__dirname, 'src'),
    publish         = path.join(__dirname, 'publish'),
    entryPathArray  = glob.sync([src, 'pages', '**', '*.js'].join('/')),
    htmlPathArray   = glob.sync([src, 'pages', '**', '*.html'].join('/'));

var entry           = entryPathArray.getEntryFiles(),
    html            = htmlPathArray.getHtmlFiles();

/* 第三方插件 */

// 自动生成页面
plugins = html; // https://github.com/jantimon/html-webpack-plugin

// 分离 css
plugins.push(new ExtractTextPlugin('css/[name].css')); // https://github.com/webpack-contrib/extract-text-webpack-plugin

/* 内置插件  https://webpack.js.org/plugins/ */

// 提取公共代买
plugins.push(new webpack.optimize.CommonsChunkPlugin('vendor'));

// 压缩代码
plugins.push(new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}}));

const config = {
  context: src,
  entry: entry,
  output: {
    path: publish,
    filename: 'js/[name].js'
  },
  module: {
    rules: [{
      test: /\.style$/,
      use: ['style-loader']
    }, {
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          'css-loader',
          'autoprefixer-loader'
        ]
      })
    }, {
      test: /\.scss$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          'css-loader',
          'autoprefixer-loader',
          'sass-loader'
        ]
      })
    }, {
      test: /\.js[x]?$/,
      exclude: /(node_modules)/,
      loader: 'babel-loader',
      query: {
        presets: ["es2015"]
      }
    }, {
      test: /\.(gif|jpg|png)$/,
      use: 'url-loader?name=[name].[ext]&publicPath=img/&outputPath=img/'
    }, {
      test: /\.(eot|svg|ttf|woff|woff2|otf)$/,
      use: 'file-loader?name=[name].[ext]&publicPath=../fonts/&outputPath=fonts/',
    }]
  },
  plugins: plugins
};

module.exports = config;
